package org.breathe.dynamic.thread.pool.core.designpattern.strategy.impl.alarmstrategy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import org.breathe.dynamic.thread.pool.core.designpattern.strategy.AlarmStrategy;
import org.breathe.dynamic.thread.pool.core.thread.BreatheDtpExecutor;
import org.breathe.thread.pool.common.entity.NotifyItem;

import java.util.Objects;
import java.util.concurrent.BlockingQueue;

/**
 * 容量报警
 * @author: breathe
 * @createTime: 2025-04-13
 */
public class CapacityAlarmStrategy implements AlarmStrategy {
    @Override
    public boolean check(BreatheDtpExecutor executor, NotifyItem notifyItem) {
        BlockingQueue<Runnable> workQueue = executor.getQueue();
        if (CollUtil.isEmpty(workQueue)) {
            return false;
        }

        if (Objects.isNull(notifyItem)) {
            return false;
        }

        int queueCapacity = executor.getQueueCapacity();
        double div = NumberUtil.div(workQueue.size(), queueCapacity, 2) * 100;
        return satisfyBaseCondition(notifyItem) && div >= notifyItem.getThreshold();
    }

    private boolean satisfyBaseCondition(NotifyItem notifyItem) {
        return notifyItem.isEnabled() && CollUtil.isNotEmpty(notifyItem.getPlatforms());
    }
}